const Recommendation = require('../models/recommendation');

const create = async (req, res) => {
  try {
    const recommendation = await Recommendation.create(req.body);
    res.status(201).json(recommendation);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '服务器内部错误' });
  }
};

const getById = async (req, res) => {
  try {
    const { id } = req.params;
    const recommendation = await Recommendation.findByPk(id);
    
    if (!recommendation) {
      return res.status(404).json({ error: '未找到推荐' });
    }
    
    res.json(recommendation);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '服务器内部错误' });
  }
};

const getAll = async (req, res) => {
  try {
    const recommendations = await Recommendation.findAll();
    res.json(recommendations);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '服务器内部错误' });
  }
};

const update = async (req, res) => {
  try {
    const { id } = req.params;
    const [updated] = await Recommendation.update(req.body, {
      where: { id }
    });
    
    if (updated) {
      const recommendation = await Recommendation.findByPk(id);
      res.json(recommendation);
    } else {
      res.status(404).json({ error: '推荐未找到' });
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '服务器内部错误' });
  }
};

const remove = async (req, res) => {
  try {
    const { id } = req.params;
    const deleted = await Recommendation.destroy({
      where: { id }
    });
    
    if (deleted) {
      res.status(204).send();
    } else {
      res.status(404).json({ error: '未找到推荐' });
    }
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: '服务器内部错误' });
  }
};

module.exports = { create, getById, getAll, update, remove };